package com.qingge.springboot.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingge.springboot.common.Result;
import com.qingge.springboot.entity.Course;
import com.qingge.springboot.entity.Score;
import com.qingge.springboot.entity.User;
import com.qingge.springboot.service.ICourseService;
import com.qingge.springboot.service.IScoreService;
import com.qingge.springboot.service.IUserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: Mr.Wu
 * @create: 2022-11-30 20:31
 **/
@RestController
@RequestMapping("/score")
public class ScoreController {

    @Resource
    private IScoreService scoreService;

    @Resource
    private IUserService userService;

    @Resource
    private ICourseService courseService;

    @Resource
    private ICourseService iCourseService;

    @GetMapping("/getScore/{id}")
    public Result getScore(@PathVariable Integer id){
        //通过id查询分数
        List<Score> scores = scoreService.getBaseMapper().selectList(new LambdaQueryWrapper<>(Score.class).eq(Score::getStuNo, id));
        JSONObject jsonObject = new JSONObject();
        scores.stream().forEach(item->{
            jsonObject.set(item.getCourseName(),item.getScore());
        });
        return Result.success(jsonObject);
    }

    @GetMapping("/select")
    public Result getStuScore(@RequestParam(name = "username",required = false) String username,@RequestParam Integer pageSize,@RequestParam Integer pageNum){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasLength(username),User::getUsername,username).eq(User::getRole,"ROLE_STUDENT");
        Page<User> userPage = userService.getBaseMapper().selectPage(new Page<>(pageNum, pageSize), queryWrapper);
        List<User> objects =userPage.getRecords();
        JSONArray jsonArray = new JSONArray();
        //获取所有课程信息
        List<Course> course = courseService.list();
        objects.stream().forEach(obj->{
            JSONObject jsonObject = new JSONObject(obj);
            //查询成绩信息
            LambdaQueryWrapper<Score> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Score::getStuNo,obj.getUsername());
            List<Score> scores = scoreService.getBaseMapper().selectList(wrapper);
            scores.forEach(item->{
                jsonObject.set(item.getCourseName().toString(),item.getScore());
            });
            jsonArray.add(jsonObject);
        });
        //数据整理
        Page<Object> jsonObjectPage = new Page<>();
        List<Object> collect = jsonArray.stream().collect(Collectors.toList());
        jsonObjectPage.setRecords(collect);
        jsonObjectPage.setTotal(userPage.getTotal());
        return Result.success(jsonObjectPage);
    }

    @PostMapping("/updateFen/{stuNo}")
    public Result updateFen(@PathVariable String stuNo,@RequestBody Map<String,String> map){
        //查看是否有此科目分数
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            if(StringUtils.hasLength(next.getValue())){
                //有分数，查询原本是否有分数
                LambdaQueryWrapper<Score> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(Score::getStuNo,stuNo).eq(Score::getCourseName,next.getKey());
                Score score = scoreService.getBaseMapper().selectOne(lambdaQueryWrapper);
                if(score!=null){
                    //有值，执行修改操作
                    LambdaUpdateWrapper<Score> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.set(Score::getScore,next.getValue()).eq(Score::getStuNo,stuNo).eq(Score::getCourseName,next.getKey());
                    boolean update = scoreService.update(updateWrapper);
                }else{
                    //新增记录
                    Score addscore = new Score();
                    addscore.setStuNo(stuNo);
                    addscore.setCourseName(next.getKey());
                    //查询科目编号
                    Course one = iCourseService.getOne(new LambdaQueryWrapper<>(Course.class).eq(Course::getName, next.getKey()));
                    addscore.setScore(Float.valueOf(next.getValue()));
                    addscore.setCourse(one.getId());
                    scoreService.save(addscore);
                }
            }
        }
        return Result.success();
    }

    @GetMapping("/getZc")
    public Result getZc(){
        List<Course> list = courseService.list();
        return Result.success(list);
    }
}
